package tunnel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import des.DesEncryptDecrypt;


public class RemoteSocket {
	
	Socket remoteSocket;
	
	String host;
	int port;
	public RemoteSocket() {
		this("127.0.0.1",80);
	}
	
	public RemoteSocket(String host, int port) {
		this.host = host;
		this.port = port;
		
		
	}
	
	public void connect() {
		try {
			remoteSocket = new Socket(host, port);
			remoteSocket.setReuseAddress(true);
		} catch (UnknownHostException e) {
			System.out.println("Konnte Zielserver nicht erreichen");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IO Exception??");
			e.printStackTrace();
		}
	}
	
	public byte[] sendData(byte[] zusenden, int length) {
		
		try {
			System.out.println("Sende an RemoteSocket unverschlüsselt (" + length + ")");
			OutputStream out = remoteSocket.getOutputStream();
			out.write(zusenden, 0, length);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public byte[] sendDataDESEncrypted(byte[] zusenden, int length, String pass) {
		System.out.println("Sende an RemoteSocket verschlüsselt (" + length + ")");
		byte[] decode = new byte[length];
		for(int i=0;i<length;i++) {
			decode[i] = zusenden[i];
		}
		try {
			OutputStream out = remoteSocket.getOutputStream();
			out.write(DesEncryptDecrypt.encode(decode, pass ));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	
	public int readData() {
		
		InputStream in;
		try {
			in = remoteSocket.getInputStream();
			int fromServer;
			remoteSocket.setSoTimeout(20000);
			if((fromServer = in.read()) != -1) {
			    //System.out.println("Entfernter Server: " + fromServer);
				return fromServer;
			} else {
				System.out.println("Antwort ZuEnde");
				return -1;
			}
		} catch (IOException e) {
			System.out.println("read TimeOut");
			return -2;
		}
	}
	
	public String readDataDES(String pass) {
		InputStream in;
		try {
			in = remoteSocket.getInputStream();
			remoteSocket.setSoTimeout(20000);
			return new String( DesEncryptDecrypt.decode(in, pass ) );
			
		} catch (IOException e) {
			// Timeout
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public void close() {
		try {
			if(remoteSocket != null)
				remoteSocket.close();
		} catch (IOException e) {
			System.out.println("IO Exception beim Schließen des Sockets");
			e.printStackTrace();
		}
	}

}
